package com.ym.utils;

import java.io.*;
import java.util.*;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 读取Excel
 *
 * @author zengwendong
 */
public class ReadExcelUtils {
    private Logger logger = LoggerFactory.getLogger(ReadExcelUtils.class);
    private Workbook wb;
    private Sheet sheet;
    private Row row;

    public ReadExcelUtils(POIFSFileSystem fs) {
        try {
            wb = new HSSFWorkbook(fs);
        } catch (FileNotFoundException e) {
            logger.error("FileNotFoundException", e);
        } catch (IOException e) {
            logger.error("IOException", e);
        }
    }

    /**
     * 读取Excel表格表头的内容
     *
     * @return String 表头内容的数组
     * @author zengwendong
     */
    public String[] readExcelTitle() throws Exception{
        if(wb==null){
            throw new Exception("Workbook对象为空！");
        }
        sheet = wb.getSheetAt(0);
        row = sheet.getRow(0);
        // 标题总列数
        int colNum = row.getPhysicalNumberOfCells();
        System.out.println("colNum:" + colNum);
        String[] title = new String[colNum];
        for (int i = 0; i < colNum; i++) {
            // title[i] = getStringCellValue(row.getCell((short) i));
            title[i] = row.getCell(i).getCellFormula();
        }
        return title;
    }

    /**
     * 读取Excel数据内容
     *
     * @return Map 包含单元格数据内容的Map对象
     * @author zengwendong
     */
    public List<Map<Object,Object>> readExcelContent() throws Exception{
        if(wb==null){
            throw new Exception("Workbook对象为空！");
        }
        Map<Integer, Map<Object,Object>> content = new HashMap<Integer, Map<Object,Object>>();
        sheet = wb.getSheetAt(0);
        // 得到总行数
        int rowNum = sheet.getLastRowNum();
        row = sheet.getRow(0);
        int colNum = row.getPhysicalNumberOfCells();
        // 正文内容应该从第二行开始,第一行为表头的标题
        String[] headers = {"id","bank_collect_number", "user_name", "money", "remarks", "bank_name", "bank_branch_name", "province", "city", "bank_transfer_number", "type","remarks1"};
        for (int i = 1; i <= rowNum; i++) {
            row = sheet.getRow(i);
            int j = 0;
            Map<Object,Object> cellValue = new HashMap<Object, Object>();
            while (j < colNum) {
                Object obj = getCellFormatValue(row.getCell(j));
                cellValue.put(headers[j], obj);
                j++;
            }
            content.put(i, cellValue);
        }
        List<Map<Object,Object>> list = new ArrayList<Map<Object,Object>>();
        for (int i = 1; i <= content.size(); i++) {
            Map map1 = content.get(i);
            list.add(map1);
        }
        return list;
    }
    /**
     * 读取Excel数据内容转账失败
     *
     * @return Map 包含单元格数据内容的Map对象
     * @author zengwendong
     */
    public List<Map<Object,Object>> readExcelContentNo() throws Exception{
        if(wb==null){
            throw new Exception("Workbook对象为空！");
        }
        Map<Integer, Map<Object,Object>> content = new HashMap<Integer, Map<Object,Object>>();
        sheet = wb.getSheetAt(0);
        // 得到总行数
        int rowNum = sheet.getLastRowNum();
        row = sheet.getRow(0);
        int colNum = row.getPhysicalNumberOfCells();
        // 正文内容应该从第二行开始,第一行为表头的标题
        String[] headers = {"id","bank_collect_number", "user_name", "money", "remarks", "bank_name", "bank_branch_name", "province", "city", "bank_transfer_number", "type","remarks1","transfer_number","remarks_no"};
        for (int i = 1; i <= rowNum; i++) {
            row = sheet.getRow(i);
            int j = 0;
            Map<Object,Object> cellValue = new HashMap<Object, Object>();
            while (j < colNum && j<headers.length) {
                Object obj = getCellFormatValue(row.getCell(j));
                cellValue.put(headers[j], obj);
                j++;
            }
            content.put(i, cellValue);
        }
        List<Map<Object,Object>> list = new ArrayList<Map<Object,Object>>();
        for (int i = 1; i <= content.size(); i++) {
            Map map1 = content.get(i);
            list.add(map1);
        }
        return list;
    }
    /**
     *
     * 根据Cell类型设置数据
     *
     * @param cell
     * @return
     * @author zengwendong
     */
    private Object getCellFormatValue(Cell cell) {
        Object cellvalue = "";
        if (cell != null) {
            // 判断当前Cell的Type
            switch (cell.getCellType()) {
                case Cell.CELL_TYPE_NUMERIC:// 如果当前Cell的Type为NUMERIC
                case Cell.CELL_TYPE_FORMULA: {
                    // 判断当前的cell是否为Date
                    if (DateUtil.isCellDateFormatted(cell)) {
                        // 如果是Date类型则，转化为Data格式
                        // data格式是带时分秒的：2013-7-10 0:00:00
                        // cellvalue = cell.getDateCellValue().toLocaleString();
                        // data格式是不带带时分秒的：2013-7-10
                        Date date = cell.getDateCellValue();
                        cellvalue = date;
                    } else {// 如果是纯数字

                        // 取得当前Cell的数值
                        cellvalue = String.valueOf(cell.getNumericCellValue());
                    }
                    break;
                }
                case Cell.CELL_TYPE_STRING:// 如果当前Cell的Type为STRING
                    // 取得当前的Cell字符串
                    cellvalue = cell.getRichStringCellValue().getString();
                    break;
                default:// 默认的Cell值
                    cellvalue = "";
            }
        } else {
            cellvalue = "";
        }
        return cellvalue;
    }

    /**
     * 读取Excel数据内容
     *
     * @return Map 包含单元格数据内容的Map对象
     * @author zengwendong
     */
    public List<Map<Object,Object>> readJumpUrlExcelContent() throws Exception{
        if(wb==null){
            throw new Exception("Workbook对象为空！");
        }
        Map<Integer, Map<Object,Object>> content = new HashMap<Integer, Map<Object,Object>>();
        sheet = wb.getSheetAt(0);
        // 得到总行数
        int rowNum = sheet.getLastRowNum();
        row = sheet.getRow(0);
        int colNum = row.getPhysicalNumberOfCells();
        // 正文内容应该从第二行开始,第一行为表头的标题
        String[] headers = {"pageName","pageUrl", "remark"};
        for (int i = 1; i <= rowNum; i++) {
            row = sheet.getRow(i);
            int j = 0;
            Map<Object,Object> cellValue = new HashMap<Object, Object>();
            while (j < colNum) {
                Object obj = getCellFormatValue(row.getCell(j));
                cellValue.put(headers[j], obj);
                j++;
            }
            content.put(i, cellValue);
        }
        List<Map<Object,Object>> list = new ArrayList<Map<Object,Object>>();
        for (int i = 1; i <= content.size(); i++) {
            Map map1 = content.get(i);
            list.add(map1);
        }
        return list;
    }

    public static void main(String[] args) {
//        try {
//
//            String filepath = "C:\\Users\\dhf\\Documents\\WeChat Files\\danhefei\\Files\\手工导出_20181130140000.xls";
//            File file = new File(filepath);
//            ReadExcelUtils excelReader = new ReadExcelUtils(file.getPath());
//            List list = new ArrayList();
//
//            // 对读取Excel表格内容测试
//            list = excelReader.readExcelContent();
//            System.out.println("list的内容:"+list.toString());
//        } catch (FileNotFoundException e) {
//            System.out.println("未找到指定路径的文件!");
//            e.printStackTrace();
//        }catch (Exception e) {
//            e.printStackTrace();
//        }
    }

}
